package system

import (
	"io/ioutil"
	"mi/internal/xpath"
	"os"
	"path/filepath"
	"time"
)

func UseCaseSensitiveFileNames() bool {
	return false
}

func NewLine() string {
	return "\n"
}

func ExecutingFilePath() string {
	path, _ := os.Executable()
	return xpath.NormalizePath(path)
}

func CurrentDirectory() string{
	return xpath.NormalizePath(os.Args[0])
}

func CurrentMillisecond() int64 {
	return time.Now().UnixNano()/ 1e6
}

type dirInfo struct {
	modTime int64
	infos []os.FileInfo
}
var cache = make(map[string]dirInfo)
func ReadDir(dir string) ([]os.FileInfo, error) {
	info, err := os.Stat(dir)
	if err != nil {
		return nil, err
	}
	if data, ok := cache[dir]; ok {
		if info.ModTime().UnixNano() == data.modTime {
			return data.infos, nil
		}
	}

	data, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, err
	}
	cache[dir] = dirInfo{
		modTime: info.ModTime().UnixNano(),
		infos:   data,
	}
	return data, nil
}

func GetDirs(root string) ([]string, error) {
	var result []string
	result = append(result, root)

	infos, err := ReadDir(root)
	if err != nil {
		return nil, err
	}

	for _, info := range infos {
		if info.IsDir() {
			var dir = filepath.Join(root, info.Name())
			ds, err := GetDirs(dir)
			if err != nil {
				return nil, err
			}
			result = append(result, ds...)
		}
	}

	return result, nil
}